package com.rlyy.rsj.dao;

import com.rlyy.rsj.table.SYS_BIL_STATUS;
import com.rlyy.rsj.utils.UniqueID;
import common.util.CommonUtil;

import java.sql.Connection;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

public class BilDao extends BaseDao {

    private static final String tableName = "sys.sys_bill";
    private static final BilDao instance = new BilDao();
    private static final String allColumns = "bill_id,bill_orgp_id,bill_org_id" +
            ",bill_prod_id,bill_prod_name,bill_month,bill_curusetotal" +
            ",bill_buytotal,bill_currenum,bill_curmonusenum,bill_confirm";

    public static BilDao getInstance() {
        return instance;
    }


    public int insertBilCurMonth(String orgId, final Map<String, Object> map) {
        return (int) invokeSql(conn -> {
            String sql = String.format(insertOrUpdateSql, tableName, "bill_id,bill_orgp_id,bill_org_id,bill_prod_id" +
                            ",bill_prod_name,bill_month,bill_curusetotal,bill_buytotal,bill_currenum,bill_confirm"
                    , "?,?,?,?,?,?,?,?,%s,?", "bill_orgp_id,bill_month", "bill_curusetotal=?,bill_currenum=%s");

            String orgp_id = (String) map.get("Orgp_Id");// 合同id
            // orgId
            String orgp_prod_id = (String) map.get("Orgp_Prod_Id");
            String orgp_prod_name = (String) map.get("Orgp_Prod_Name");
            String currMonth = new SimpleDateFormat("yyyy-MM").format(new Date());
            long bill_curusetotal = CommonUtil.safeLong((String) map.get("Orgp_Useamount"));
            long bill_buytotal = CommonUtil.safeLong((String) map.get("Orgp_Buyamount"));
            // orgp_billmethod
            long bill_currenum = bill_buytotal - bill_curusetotal;
            if (bill_currenum < 0) {
                bill_currenum = 0L;
            }
            // 0

            sql = String.format(sql, bill_currenum, bill_currenum);

            return getQueryRunner().update(conn, sql,
                    UniqueID.generateId(),
                    orgp_id, orgId, orgp_prod_id, orgp_prod_name
                    , currMonth, bill_curusetotal, bill_buytotal,
                    SYS_BIL_STATUS.confNo, bill_curusetotal
            );
        });
    }

    public void updateCure(Connection conn) throws SQLException {
        getQueryRunner().update(conn, "UPDATE sys.sys_bill SET bill_curmonusenum " +
                " = b.bill_current FROM " +
                " ( SELECT bill_id AS ID,(bill_curusetotal - LAG ( bill_curusetotal, 1, 0 ) " +
                " OVER ( PARTITION BY bill_orgp_id ORDER BY bill_month )) AS bill_current " +
                " FROM sys.sys_bill as bill ) AS b WHERE sys_bill.bill_id = b.ID;");
    }
}
